<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="章节名称" prop="chapterName">
        <el-input
          v-model="queryParams.chapterName"
          placeholder="请输入章节名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
    
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:chapter:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="chapterList"
      row-key="chapterId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="章节名称" prop="chapterName" />
      <el-table-column label="父章节名称" align="center">
        <template #default="scope">
          <span>{{ getParentChapterName(scope.row.parentId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:chapter:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['manage:chapter:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:chapter:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改章节管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="chapterRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="章节名称" prop="chapterName">
          <el-input v-model="form.chapterName" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="父章节" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="chapterOptions"
            :props="{ value: 'chapterId', label: 'chapterName', children: 'children' }"
            value-key="chapterId"
            placeholder="请选择父章节"
            check-strictly
            @change="handleParentChange"
          />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-select v-model="form.orderNum" placeholder="请选择显示顺序">
            <el-option
              v-for="num in availableOrderNums"
              :key="num"
              :label="num"
              :value="num"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Chapter">
import { listChapter, getChapter, delChapter, addChapter, updateChapter } from "@/api/manage/chapter";

const { proxy } = getCurrentInstance();

const chapterList = ref([]);
const flatChapterList = ref([]); // 扁平化章节列表，用于查找父章节
const chapterOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);
const availableOrderNums = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    chapterName: null,
    parentId: null,
    orderNum: null,
  },
  rules: {
    chapterName: [
      { required: true, message: "章节名称不能为空", trigger: "blur" }
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询章节管理列表 */
function getList() {
  loading.value = true;
  listChapter(queryParams.value).then(response => {
    // 保存扁平章节列表用于查找父章节
    flatChapterList.value = response.data || [];
    // 转换为树形结构
    chapterList.value = proxy.handleTree(response.data, "chapterId", "parentId");
    loading.value = false;
  });
}

/** 查询章节管理下拉树结构 */
function getTreeselect() {
  listChapter().then(response => {
    chapterOptions.value = [];
    const data = { chapterId: 0, chapterName: '离散数学', children: [] };
    data.children = proxy.handleTree(response.data, "chapterId", "parentId");
    chapterOptions.value.push(data);
  });
}

// 获取父章节名称
function getParentChapterName(parentId) {
  if (!parentId || parentId === '0' || parentId === 0) {
    return '离散数学';
  }
  
  // 在扁平列表中查找父章节
  const parentChapter = flatChapterList.value.find(item => item.chapterId == parentId);
  // 如果找不到父章节，返回"未知章节"而不是ID
  return parentChapter ? parentChapter.chapterName : '未知章节';
}

// 处理父节点变化
function handleParentChange(value) {
  // 重置显示顺序
  form.value.orderNum = null;
  
  // 确保value是数字类型
  const parentId = typeof value === 'string' ? parseInt(value) : value;
  
  // 获取同级节点数量
  const getSiblingCount = () => {
    if (!parentId || parentId === 0) {
      return chapterList.value.length;
    }
    const findParentNode = (list) => {
      for (const item of list) {
        if (item.chapterId === parentId || parseInt(item.chapterId) === parentId) {
          return item.children ? item.children.length : 0;
        }
        if (item.children) {
          const count = findParentNode(item.children);
          if (count !== undefined) return count;
        }
      }
    };
    return findParentNode(chapterList.value);
  };

  // 获取已使用的顺序号
  const getUsedOrderNums = () => {
    const usedNums = new Set();
    const findSiblings = (list) => {
      for (const item of list) {
        const itemParentId = typeof item.parentId === 'string' ? parseInt(item.parentId) : item.parentId;
        if (itemParentId === parentId && item.chapterId !== form.value.chapterId) {
          usedNums.add(item.orderNum);
        }
        if (item.children) {
          findSiblings(item.children);
        }
      }
    };
    findSiblings(chapterList.value);
    return usedNums;
  };

  const siblingCount = getSiblingCount();
  const usedNums = getUsedOrderNums();
  
  // 生成可选的顺序号（1到当前数量+1）
  availableOrderNums.value = Array.from(
    { length: siblingCount + 1 },
    (_, i) => i + 1
  ).filter(num => !usedNums.has(num));
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    chapterId: null,
    chapterName: null,
    parentId: null,
    orderNum: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("chapterRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
async function handleAdd(row) {
  reset();
  await getTreeselect();
  if (row != null && row.chapterId) {
    // 确保父章节ID是数字类型
    form.value.parentId = typeof row.chapterId === 'string' ? parseInt(row.chapterId) : row.chapterId;
    handleParentChange(form.value.parentId);
  } else {
    form.value.parentId = 0;
    handleParentChange(0);
  }
  open.value = true;
  title.value = "添加章节管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  getChapter(row.chapterId).then(response => {
    form.value = response.data;
    // 确保parentId是数字类型而不是字符串
    if (form.value.parentId) {
      form.value.parentId = parseInt(form.value.parentId);
    }
    handleParentChange(form.value.parentId);
    open.value = true;
    title.value = "修改章节管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["chapterRef"].validate(valid => {
    if (valid) {
      if (form.value.chapterId != null) {
        updateChapter(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addChapter(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除章节管理编号为"' + row.chapterId + '"的数据项？').then(function() {
    return delChapter(row.chapterId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>